﻿#include "savetask.h"
#include <QDebug>
#include <QtEndian>

SaveTask::SaveTask(QImage image, QString path, QByteArray message)
    : m_image(image)
    , m_strSavePath(path)
    , assist_message(message)
{
//传入图片信息和保存路径
}
//保存图片
bool SaveTask::saveImage()
{
    bool ret = false;
    if(!m_image.isNull()&& !m_strSavePath.isEmpty()){

        int bytesPerLine = m_image.bytesPerLine();//每行字节数
        int height = m_image.height();
        int width = m_image.width();
        uchar* imageData = m_image.bits();//图片数组头指针
        QByteArray byteArray((char*)imageData, bytesPerLine * height); //将QImage转换为QByteArra

        //针对坏行相机进行补偿
//        char *data_head = byteArray.data();
//        QByteArray replace_forty_six, replace_forty_seven;
//        for(int i = 0; i < bytesPerLine/2; ++i){
//            replace_forty_six.append(ShortToArray(qFromBigEndian(static_cast<unsigned short>((*(unsigned short*)(data_head+bytesPerLine*45+2*i)+*(unsigned short*)(data_head+bytesPerLine*45+2*(i+1)))/2))));
//        }
//        for(int i = 0; i < bytesPerLine/2; ++i){
//            replace_forty_seven.append(ShortToArray(qFromBigEndian(static_cast<unsigned short>((*(unsigned short*)(data_head+bytesPerLine*48+2*i)+*(unsigned short*)(data_head+bytesPerLine*48+2*(i+1)))/2))));
//        }
//        byteArray.replace(bytesPerLine*46,bytesPerLine,replace_forty_six);
//        byteArray.replace(bytesPerLine*47,bytesPerLine,replace_forty_seven);

        QByteArray append_data;
        append_data.resize(bytesPerLine);
        append_data.fill(0); //全部写0
        append_data.replace(0,sizeof(assist_message),assist_message); //替换想要添加的内容
        byteArray.append(append_data);


        QImage all_image((uchar*)byteArray.data(),width,height+1,QImage::Format_Grayscale16);
        ret = all_image.save(m_strSavePath/*, nullptr, 100*/);
    }else{
        return false;
    }
    return ret;
}

QString SaveTask::path()
{
    return m_strSavePath;
}

QByteArray SaveTask::ShortToArray(unsigned short v)
{
    int size = sizeof (unsigned short);

    QByteArray a;
    a.resize(size);

    for(int i = 0; i < size; i++){
        a[i] = static_cast<char>( (v >> ( (size - i -1) * 8) ) & 0xff );
    }

    return a;
}
